package ru.kradef.taxi.service;

import java.io.Serializable;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpRequest implements Serializable {

    private static final long serialVersionUID = -238422847340823837L;
    private HttpMethod method;
    private String query;
    private Properties headers = new Properties();
    private byte[] body;

    public enum HttpMethod {
	GET
    }

    public HttpRequest(String httpRequest) {
	httpRequest = parseRequestParams(httpRequest);
	httpRequest = parseRequestHeaders(httpRequest);
	parseRequestBody(httpRequest);
    }

    private void parseRequestBody(String httpRequest) {
	String bodyLength = headers.getProperty("Content-Length", "0");
	int length = 0;
	try {
	    length = Integer.parseInt(bodyLength);
	} catch (Exception e) {
	    return;
	}
	if (length <= 0) {
	    return;
	}
	// todo: remake parsing, request could be in bytes :(
    }

    private String parseRequestHeaders(String httpRequest) {
	Pattern pattern = Pattern.compile("([^ ]+):\\s*([^\n]+)\r\n");
	while (!httpRequest.startsWith("\r\n")) {
	    Matcher matcher = pattern.matcher(httpRequest);
	    if (!matcher.find()) {
		throw new IllegalArgumentException("Http headers coudn't be read: " + httpRequest);
	    }
	    headers.put(matcher.group(1), matcher.group(2));
	    httpRequest = httpRequest.substring(matcher.group(0).length());
	}
	// remove \r\n
	return httpRequest.substring(2);
    }

    private String parseRequestParams(String httpRequest) {
	Pattern pattern = Pattern.compile("^(GET)\\s+([^\\s]+)\\s+HTTP/1\\.\\d\r\n(.+)$", Pattern.DOTALL);
	Matcher matcher = pattern.matcher(httpRequest);
	if (!matcher.find()) {
	    throw new IllegalArgumentException("Http request is unrecognized: " + httpRequest);
	}
	method = HttpMethod.valueOf(matcher.group(1));
	query = matcher.group(2);

	return matcher.group(3);
    }

    @Override
    public String toString() {
	return "HttpRequest [method=" + method + ", query=" + query + ", headers=" + headers + "]";
    }

}
